<template>
  <div class='q-pa-md'>
    <q-table :columns='columns' :filter='filter' :loading='loading' :rows='rows' binary-state-sort row-key='id'
      title='Treats' @request='onRequest' no-data-label='!' v-model:pagination="pagination">
      <template v-slot:top-left>
        <div class='row'>
          <div class='col-4' style='min-width: 250px; max-width: 300px' @mouseover='mouseover'>
            <q-select v-model='mulSelect.arr' filled label='选择项' multiple name='search' stack-label use-chips />
          </div>
          <div class='col-2'>
            <q-btn color='white' icon='search' text-color='black' @click='fetchFromServer' />
          </div>
        </div>
        <div class='q-pt-md row justify-start items-center'>
          <div v-for='(item, index) in searchFrame' :key='index' class='q-px-md'>

            <div v-if='item.property_code == "confirm_date"' class='q-pa-md'>
              <q-btn color='primary' :label='item.property_name' @click='qdateShow = true' />
              <q-date v-model='qdateModel' range v-show='qdateShow' @range-end='qdateRangeEnd(index)'
                style='position:absolute;top: 140px;left: 47px;z-index: 100' />
            </div>

            <!--这个是车架号单独出来的搜索框-->
            <div v-else-if='item.property_code == "vin"'>
              <q-select ref='selections' filled v-model="carNo" @input-value='handelValue'
                @update:model-value='searchVale' use-input input-debounce="0" :label=item.property_name
                :options="options" style="width: 300px">
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      No results
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </div>
            <q-btn-dropdown v-else :label='item.property_name' class='col-4' color='primary'
              @click='onQueryBar(index + 1, item.property_name)'>
              <q-list v-for='item in searchFrameArr1' :key='item.markNo'>
                <q-item v-close-popup clickable @click='searchClick(item, index)'>
                  <q-item-section>
                    <q-item-label>
                      {{ item.value }}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>

            <q-date v-model='qdateModel' range v-show='qdateShow' @range-end='qdateRangeEnd(index)'
              style='position:absolute;top: 140px;left: 47px;z-index: 100' />
          </div>
        </div>

      </template>

      <template v-slot:top-right>
        <div class='inBigTitle'>
          {{ userData.levelType + "." + userData.levelName }}
        </div>
        <div v-if='entityCode == "201"'>
          <q-btn class='control-btn' color='primary' label='类型' @click='toType' />
        </div>
        <q-btn v-if='pageDataModified' label='提交' @click='batchUpdate' />
        <q-btn label='打印' @click='printData' />
        <q-btn v-for='(item, index) in globalOperation' :key='index' :label='item.operateEventName' class='control-btn'
          color='primary' @click='toAdd(item)' />
        <!--        <q-btn  label='导出' @click='exportHr' />-->
        <q-btn label='返回' @click='goBack()' />
      </template>

      <template v-slot:header='props'>
        <q-tr :props='props'>
          <template v-for='col in props.cols' :key='col.name' :props='props'>
            <template v-if='col.name == "control"'>
              <q-th align='left' class='sticky-col'>
                {{ col.label }}
              </q-th>
            </template>
            <template v-else-if='col.name == "detail"'>
              <q-th align='left' class='sticky-col'>
                {{ col.label }}
              </q-th>
            </template>
            <template v-else-if='col.name == "subject"'>
              <q-th align='left' class='sticky-col'>
                {{ col.label }}
              </q-th>
            </template>
            <template v-else>
              <q-th align='left'>
                {{ col.label }}
              </q-th>
            </template>
          </template>
        </q-tr>
      </template>
      <template v-slot:body='props'>
        <q-tr :props='props'>
          <template v-for='col in props.cols' :key='col.name' :props='props'>
            <template v-if='col.name == "control"'>
              <q-td class='sticky-col'>
                <q-btn-dropdown v-if='operationFirstSelections.operateEventName !== undefined'
                  :label='operationFirstSelections.operateEventName' split
                  @click='topOperation(props.row, operationFirstSelections)'>
                  <q-list v-for='(item, index) in operationSelections' :key='index'>
                    <q-item v-close-popup clickable @click='topOperation(props.row, item)'>
                      <q-item-section>
                        <q-item-label>{{ item.operateEventName }}</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-btn-dropdown>
              </q-td>
            </template>
            <template v-else-if='col.name == "detail"'>
              <q-td class='sticky-col'>
                <!-- 第一列的详情按钮 -->
                <q-btn v-if='entityCode !== "702"' color='primary' label='详情' @click='toDetail(props.row)' />
                <q-btn v-else color='primary' label=''><a class='detail' :href='props.row.report_url'
                    target="_blank">详情</a></q-btn>
              </q-td>
            </template>
            <template v-else-if='col.name == "subject"'>
              <q-td class='sticky-col' @click='bindItems(props.row)'>
                <q-btn-dropdown v-if='entityCode !== "702"' :label='relationFirstSelection.arr.relationName' split
                  @click='toRelation(props.row, relationFirstSelection.arr)'>
                  <q-list v-for='(item, index) in relationSelection.arr' :key='index'>
                    <q-item v-close-popup clickable @click='toRelation(props.row, item)'>
                      <q-item-section>
                        <q-item-label>{{ item.relationName }}</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-btn-dropdown>
                <q-btn-dropdown v-else :label='relationFirstSelection.arr.relationName' split
                  @click='jumpToUrl(props.row.report_best_url)'>
                  <q-list v-for='(item, index) in relationSelection.arr' :key='index'>
                    <q-item v-close-popup clickable @click='toRelation(props.row, item)'>
                      <q-item-section>
                        <q-item-label v-if='item.relationCode == "70191002"'>
                          <a :href='props.row.report_jd_url' target="_blank">{{ item.relationName }}</a>
                        </q-item-label>
                        <q-item-label v-if='item.relationCode == "70191003"'>
                          <a :href='props.row.report_best_url' target="_blank">{{ item.relationName }}</a>
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                  <q-list v-if='orderNowStat'>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          <a @click='toCert(props.row, relationFirstSelection.arr)'
                            style="text-decoration: underline;cursor:pointer" target="_blank">三无证书</a>
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          <a @click='toSanwuReport(props.row, relationFirstSelection.arr)'
                            style="text-decoration: underline;cursor:pointer" target="_blank">升级版报告（三无）</a>
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          <a @click='toCreport(props.row, relationFirstSelection.arr)'
                            style="text-decoration: underline;cursor:pointer" target="_blank">C端报告</a>
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          <a @click='toNewCert(props.row, relationFirstSelection.arr)'
                            style="text-decoration: underline;cursor:pointer" target="_blank">升级版报告</a>
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          <a @click='toNewCertPaint(props.row, relationFirstSelection.arr)'
                            style="text-decoration: underline;cursor:pointer" target="_blank">升级版报告(漆面)</a>
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          <a @click='toReportCover(props.row, relationFirstSelection.arr)'
                            style="text-decoration: underline;cursor:pointer" target="_blank">升级版报告(模版)</a>
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-btn-dropdown>
              </q-td>
            </template>
            <template v-else-if='col.name == "serveNo"'>
              <q-td>
                <q-btn flat color='primary' :label=props.row.serveNoC @click='ToactivityDetails(props.row.serveNo)' />
              </q-td>
            </template>
            <template v-else>
              <q-td @click="handleTableRowClick(props.row)">
                {{ props.row[col.name] }}
                <q-popup-edit v-if='editAble(col.name, props.row["accessory3"])' v-model="props.row[col.name]"
                  v-slot="scope" auto-save>
                  <q-input v-model="scope.value" dense autofocus @keyup.enter="scope.set" />
                </q-popup-edit>
                <!--                <q-popup-edit v-model="col.value" title="Update carbs" buttons persistent v-slot="scope">-->
                <!--                  <q-input  v-model="scope.value" dense autofocus hint="Use buttons to close" />-->
                <!--                </q-popup-edit>-->
              </q-td>
            </template>
            <!--            <template v-else>-->
            <!--              <q-td>-->
            <!--                {{ col.value }}-->
            <!--              </q-td>-->
            <!--            </template>-->

          </template>
        </q-tr>
      </template>
    </q-table>
  </div>
</template>
<script lang='ts'>
import { Operation, OriginalRows, Pagination, Props, recOperation, TableColumn } from 'src/components/models';
import { defineComponent, onMounted, reactive, ref, watch, onBeforeMount } from 'vue';
import { postRequest, getRequest } from '../components/functions';
import { useStore } from 'src/store';
import { CarMessage, cartypeRelation } from 'src/store/sphinx/state';
import { useRoute, useRouter } from 'vue-router';
import { api } from 'boot/axios';
import { export2Excel } from '../../vendor/FileExport';
import printJS from 'print-js'

export default defineComponent({
  name: 'TableComponent',
  setup(props,{emit}) {
    let rote = useRoute();
    let router = useRouter();
    const store = useStore();
    const queryMenu = 'channel/channel/queryMenu';
    const getInterface = '/channel/channel/getInterface';
    const userData = store.state.sphinx.userData;
    const rowMsg = store.state.sphinx.CarMessage;
    let columns = ref<TableColumn[]>();
    let operationFirstSelections = ref<recOperation>();
    let operationSelections = ref<recOperation[]>();
    let globalOperation = ref<recOperation[]>();
    const originalRows = ref<OriginalRows[]>();
    let rows = ref([]);
    const filter = ref<string>();
    const loading = ref<boolean>(true);
    const pagination = ref<Pagination>({
      sortBy: 'desc',
      descending: false,
      page: 1,
      rowsPerPage: 10,
      rowsNumber: 10000,
      // filter:10  // 一个filter
    });
    let entityCode = ref<string>('');
    let childCode = ref<string>('');
    let fromdataUrl = ref<string>('');
    let fromdataOption = ref<string>('');
    let searchFrame = ref([]);
    let searchFrameArr = ref([]);
    let mulSelect = reactive({ arr: [] });
    let QueryBarCode = reactive({ arr: [] });
    let relationFirstSelection = reactive({ arr: [] });
    let relationSelection = reactive({ arr: [] });
    let qdateModel = ref({ from: '', to: '' });
    let qdateShow = ref<boolean>(false);
    let startEndTime = ref<string>('');
    let searchFrameArr1 = ref([]);
    let treadMark = ''
    let carseries = ''
    let options = ref([])
    let arr
    let pathArr = reactive([]) // localstorage中的地址
    let path = ref("")
    const selections = ref(null)
    let originalParam = ref([])
    let selectParams = []
    let translate = []
    let carNo = ref('')
    let rowsTemp;
    let pageDataModified = ref(false)
    //当车架号文本框里面的值发生改变时触发的函数
    function handelValue(value) {
      let searchCarUrl = 'detection/detection/queryDetection';
      getRequest(searchCarUrl, (res) => {
        arr = []
        res.forEach((item, index, array) => {
          if (item.vin) {
            arr.push(item.vin);
          }
        })
        options.value = arr
        selections.value.showPopup()
      }, { keyword: value })

    }

    function goBack() {

      let seletedItem = JSON.parse(JSON.stringify(store.state.sphinx.selectedItemData));
      if (seletedItem.length > 0) {
        seletedItem.splice(seletedItem.length - 1, 1);
        store.commit('sphinx/updateSelectedItemData', seletedItem);
      }

      let parentEntity = JSON.parse(JSON.stringify(store.state.sphinx.parentEntity));
      if (parentEntity.length > 0) {
        parentEntity.splice(parentEntity.length - 1, 1);
        store.commit('sphinx/updateParentEntity', parentEntity);
      }


      let routerPath = JSON.parse(JSON.stringify(store.state.sphinx.routerPath));
      if (routerPath.length > 0) {
        let strings = routerPath.splice(routerPath.length - 1, 1);
        store.commit('sphinx/updateRouterPath', routerPath);
        router.push("/")
        if (strings !== undefined) {
          setTimeout(() => {
            router.push(strings[0])
          }, 300)
        }
      }


    }
    function searchVale(value) {
      mulSelect.arr.push(value);
      let obj = {};
      obj["keyword"] = value;
      QueryBarCode.arr.push(obj);
      mulSelect.arr = Array.from(new Set(mulSelect.arr));
    }
    //点击下拉的数据展示在搜索框里
    function searchClick(item: any, index: number) {
      let itemElement = searchFrame.value[index].property_code;
      mulSelect.arr.push(item.value);
      console.log("xpa123 itemElement", itemElement);
      console.log("xpa123 item.value", item.value);
      let obj = {};
      obj[itemElement] = item.value;
      QueryBarCode.arr.push(obj);
      if (itemElement === 'markName') {
        treadMark = item.no;
      } else if (itemElement === 'seriesName') {
        carseries = item.no;
      }
      mulSelect.arr = Array.from(new Set(mulSelect.arr));

      //主体808账户进行特殊处理，选中查询条件月份后进行月份查询
      if (entityCode.value == "808") {

        //准备查询条件
        //  let item = {};

        let selectedItemDatum = store.state.sphinx.selectedItemData[store.state.sphinx.selectedItemData.length - 1];
        let item2: any = {};
        if (selectedItemDatum !== undefined) {
          let s = JSON.stringify(selectedItemDatum);
          let swap = JSON.parse(s)
          //获取跳转过来的实体参数
          let prevOptEntity = store.state.sphinx.prevOptEntity;
          console.log('跳转前的主体记录swap', swap)


          item2["accessory4"] = item.value;
          item2["companyId"] = userData.companyId;
          item2["entityCode"] = entityCode.value;
          item2["entityType"] = childCode.value;;
          item2["remark2"] = swap["remark2"];
          console.log('跳转前的主体记录swapswap["remark2"]', swap["remark2"])
        }

        //开始查询
        console.log('808账户选中查询条件月份后进行月份查询', item)
        getRequest(fromdataUrl.value, data => {
          searchFrame.value = [];
          a = false;
          // mulSelect.arr.length = 0;
          console.log("808账户输出数据2，data", data);
          rows.value = transformFuncs(data);  // 表格数据
          // console.log("rows.value",rows.value);
          // pagination.value.rowsNumber = rows.value.length; // 数据总数
          loading.value = false;
        }, item2);

      }


    }

    //点击日期数据展示在搜索框里
    function qdateRangeEnd(index) {
      let itemElement = searchFrame.value[index].property_code;
      let obj = {};

      let startTime = qdateModel.value.from;
      let endTime = qdateModel.value.to;
      startEndTime.value = startTime.split('/').join('-') + '/' + endTime.split('/').join('-');
      mulSelect.arr.push(startEndTime.value);
      mulSelect.arr = Array.from(new Set(mulSelect.arr));

      obj[itemElement] = startEndTime.value;
      QueryBarCode.arr.push(obj);

      setTimeout(() => {
        qdateShow.value = false;
        qdateModel.value = { from: '', to: '' };
      }, 1000);
    }

    // 点击搜索框获取数据
    function onQueryBar(i, y) {
      //获取搜索数据的接口
      console.log("onQueryBar");
      let resData = {
        entityCode: entityCode.value,
        entityType: childCode.value + '1070' + i,
        theirEventCode: '001'
      };

      let QueryBarUrl = ref<string>('');
      let entityType = '';
      postRequest(getInterface, resData, res => {

        entityType = res.data.entityType
        let url = res.data.interfaceEnglish;
        QueryBarUrl.value = url.substr(url.indexOf('/') + 1);
      });

      //获取搜索条件
      let resData1 = {
        companyId: userData.companyId,
        entityCode: entityCode.value,
        entityType: childCode.value,
        sceneCodeType: '101102' + userData.roleType + '103',
        objectCodeType: '1070' + i
      };
      let QueryBarData = ref({});
      let paramName = ''
      postRequest(queryMenu, resData1, res => {
        res.forEach(i => {
          let obj = { entityCode: entityCode.value };
          let val = '';
          switch (y) {
            case '车系':
              val = treadMark;
              paramName = 'proCarTrademarkUuid'
              break;
            case '年款':
              val = carseries;
              paramName = 'proCarSeriesUuid'
              break;
            // case '车型':  val = getTypeValue('strleName')  ;break;
          }
          //obj[i.property_code] = val;
          obj[paramName] = val;
          QueryBarData.value = obj;
        });
      });

      // postRequest(queryMenu, resData1, res => {
      //   res.forEach(i => {
      //     let obj = {};
      //     obj[i.property_code] = '';
      //     QueryBarData.value = obj;
      //   });
      // });

      //获取搜索数据
      searchFrameArr1.value = [];
      if (entityCode.value == "702") {
        QueryBarData.value = {
          entityCode: entityCode.value,
          entityType: entityType
        }
      }
      if (entityCode.value == "510") {
        QueryBarData.value = {
          entityCode: entityCode.value,
          // entityType: childCode.value
        }
      }
      if (entityCode.value == "808") {
        QueryBarData.value = {
          entityCode: entityCode.value,
          entityType: '00'
        }
      }
      setTimeout(() => {
        if (entityCode.value == "702") {
          QueryBarData.value = {
            entityCode: entityCode.value,
            entityType: entityType
          }
        }
        console.log("xpa QueryBarUrl", QueryBarUrl.value);
        console.log("xpa QueryBarData", QueryBarData.value);
        getRequest(QueryBarUrl.value, res => {
          searchFrameArr1.value = res;
        }, QueryBarData.value);
      }, 1000);

      // setTimeout(() => {
      //   postRequest(QueryBarUrl.value, QueryBarData.value, res => {
      //     searchFrameArr.value = res;
      //   });
      // }, 1000);
    }

    // 鼠标放在搜索框上出搜索选项
    let a = false;

    async function mouseover() {
      let sceneCode = await getSceneCode()
      if (a) return;
      a = true;
      console.log("mouseover");
      let resData = {
        companyId: userData.companyId,
        entityCode: entityCode.value,
        entityType: childCode.value,//类型为00
        sceneCode: sceneCode,
        objectCodeType: '107'//代表搜索的代码
      };
      if (searchFrame === null || searchFrame?.value?.length == 0) {
        postRequest(queryMenu, resData, (res: []) => {
          searchFrame.value = res;
          a = false;
        });
      }
    }

    // 获取关联主体的关系项
    function getRelation() {
      let sceneCode = ''
      let requestSceneBody = [
        {
          "entityCode": '101',
          "codeName": '',
          "entityType": '01',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": null,
          "propertyChinese": null,
          "propertyValue": null,
          "propertyCondition": null,
          "companyId": userData.companyId
        },
        {
          "entityCode": '102',
          "codeName": '',
          "entityType": '02',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": 'roleType',
          "propertyChinese": null,
          "propertyValue": userData.roleType,
          "propertyCondition": null,
          "companyId": userData.companyId
        }];
      api.post('/channel/channel/getSceneCode', requestSceneBody).then(res => {
        if (res.status == 200) {
          sceneCode = res.data.data
          let reqData = reactive({});
          if (entityCode.value !== undefined) {
            reqData = {
              companyId: userData.companyId,
              entityCode: entityCode.value,
              entityType: childCode.value,
              sceneCode: sceneCode,//渠道101+当事人102+用户角色userData.roleType（例：01为管理员）+场景主体
              objectCodeType: '301'
            };

            postRequest('channel/channel/relation', reqData, res => {
              let arr = [];
              arr = res;
              if (res) {
                relationFirstSelection.arr = arr.splice(0, 1)[0];
              }
              relationSelection.arr = arr;
            });
          }
        }
      })
    }

    /**s
     * 请求主体首页表头
     */
    function requestColumns() {
      let sceneCode = ''
      let requestSceneBody = [
        {
          "entityCode": '101',
          "codeName": '',
          "entityType": '01',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": null,
          "propertyChinese": null,
          "propertyValue": null,
          "propertyCondition": null,
          "companyId": userData.companyId
        },
        {
          "entityCode": '102',
          "codeName": '',
          "entityType": '02',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": 'roleType',
          "propertyChinese": null,
          "propertyValue": userData.roleType,
          "propertyCondition": null,
          "companyId": userData.companyId
        }];
      api.post('/channel/channel/getSceneCode', requestSceneBody).then(res => {
        if (res.status == 200) {
          sceneCode = res.data.data;
          let reqData = reactive({});
          if (entityCode.value != undefined) {
            reqData = {
              companyId: userData.companyId,
              entityCode: entityCode.value,
              entityType: childCode.value,
              sceneCode: sceneCode,//渠道101+当事人102+用户角色userData.roleType（例：01为管理员）+场景主体
              objectCodeType: '102'//主体首页表头
            };
          }
          api.post('/channel/channel/getAuthority', {
            "companyId": userData.companyId,
            "entityCode": entityCode.value,
            "entityType": childCode.value,
            "objectCodeType": "120",
            "sceneCode": sceneCode
          }
          ).then(res => {
            originalParam.value = res.data.data;
            getFromdataUrl();
          })
          postRequest(queryMenu, reqData, getColums);
          setTimeout(() => {
            if (loading.value) {
              loading.value = false;
            }
          }, 2000);
        }
      })

    }

    /**
     * 设置列名
     * @param resultData
     */
    function getColums(resultData: TableColumn[] | any) {
      console.log("resultData", resultData);

      let newArr = [];
      if (resultData !== undefined && resultData !== null && resultData.length > 0) {
        resultData.forEach(item => {
          // console.log("item",item);

          newArr.push({ name: item.property_code, label: item.property_name, field: item.property_code });
        });

        newArr.unshift({
          name: 'detail',
          label: '详情',
          field: 'detail'
        });
        if (entityCode.value !== '702') {
          newArr.push(
            {
              name: 'control',
              label: '操作',
              field: 'control'
            });
        }
        newArr.push({
          name: 'subject',
          label: '相关主体',
          field: 'subject'
        })
        /******************/
        // newArr.push({
        //   name: 'delete',
        //   label: '删除',
        //   field: 'delete'
        // })
      }
      columns.value = newArr;
      console.log("columns", columns);

    }

    // 获取请求表内数据的接口
    function getFromdataUrl() {
      console.log("getFromdataUrl");
      let data = {
        entityCode: entityCode.value,
        entityType: '',
        theirEventCode: '001'
      }
      if (childCode.value.length == 0 || childCode.value.length == 2) {
        // if(rote.query.flag == "1"){
        //   data.entityType = childCode.value
        // }else{
        //   data.entityType = childCode.value + '99002'
        // }
        data.entityType = childCode.value
      } else {
        data.entityType = childCode.value
      }

      if (entityCode.value == '808') {
        data.theirEventCode = '100'
      }

      postRequest(getInterface, data, res => {
        getRequest("/channel/channel/queryStatus1?entityCode=" + entityCode.value + "&entityType=" + childCode.value, res => {
          translate = res
        })
        if (res.data == null) return;
        let url = res.data.interfaceEnglish;
        fromdataOption.value = url.substr(0, url.indexOf('/'));
        fromdataUrl.value = url.substr(url.indexOf('/') + 1);
        // if (entityCode.value == "802") {
        //   fromdataOption.value = 'get'
        //   fromdataUrl.value = '/transaction/agreement/queryAgreeYanbaoByNo'
        // }
        onRequest({
          pagination: pagination.value,
          filter: ''
        });
      });
    }

    let chainTail = ref('')
    let tempArray = reactive([])
    let codeValueArr = reactive([])
    let storeChainTemp = reactive([])
    /**
     * 请求表内数据
     * @param startRow
     * @param count
     * @param filter
     * @param sortBy
     * @param descending
     */
    function fetchFromServer(startRow: number, count: number, filter: string, sortBy: string, descending: boolean) {
      let selectedItemDatum = store.state.sphinx.selectedItemData[store.state.sphinx.selectedItemData.length - 1];
      let item: any = {};
      if (selectedItemDatum !== undefined) {
        let s = JSON.stringify(selectedItemDatum);
        let swap = JSON.parse(s)
        //获取跳转过来的实体参数
        let prevOptEntity = store.state.sphinx.prevOptEntity;
        console.log('跳转前的主体记录swap', swap)
        console.log('获取跳转过来的实体参数prevOptEntity', prevOptEntity)
        console.log('请求地址', "/transaction/sub/fetchChannelRoute?relationFlag=2&entityCode=" + prevOptEntity.entityCode + "&entityType=" + prevOptEntity.childCode + "&otherEntityCode=" + entityCode.value + "&otherEntityType=" + childCode.value + "&otherEventCode=null")
        api.get(
          "/transaction/sub/fetchChannelRoute?relationFlag=2&entityCode=" + prevOptEntity.entityCode + "&entityType=" + prevOptEntity.childCode + "&otherEntityCode=" + entityCode.value + "&otherEntityType=" + childCode.value + "&otherEventCode=null"

        ).then(data => {
          let tempLate = { entityCode: entityCode.value, entityType: childCode.value }
          //匹配路由参数
          for (let itm in swap) {
            data.data.data.forEach(x => {
              if (x.propertyEnglish === itm) {
                tempLate[x.otherPropertyEnglish] = swap[itm]
              }
            })
          }
          // if (fromdataOption.value == 'get') {
          //   item= tempLate
          // } else {
          //   item = swap
          // }
          //匹配到的参数
          console.log('匹配到的参数', tempLate)
          item = tempLate
          analyze()

        })
        //  getRequest("/transaction/sub/fetchChannelRoute?relationFlag=1&entityCode="+entityCode.value+"&entityType="+childCode.value,(data) => {
        //
        //
        // })
      } else {
        analyze()
      }

      function analyze() {
        let parentEntity = store.state.sphinx.parentEntity[0];
        console.log('key', store.state.sphinx.parentEntity)
        //处理搜索内容的数据
        let newArr = ref([]);
        console.log("QueryBarCode.arr", QueryBarCode.arr);
        console.log("mulSelect.arr", mulSelect.arr);

        QueryBarCode.arr.forEach(x => {
          mulSelect.arr.forEach(y => {
            if (y == Object.values(x)[0]) {
              newArr.value.push(x);
            }
          });
        });


        let target: any = {
          entityCode: entityCode.value,
          entityType: childCode.value,
          data: [],
          companyId: '',
          size: count === undefined ? 10 : count,
          page: count === undefined ? 1 : startRow / count + 1
        };

        let entityType0 = childCode.value;

        if (childCode.value == '1199') {
          entityType0 = '11';
        }
        if (childCode.value == '1299') {
          entityType0 = '12';
        }

        let target99 = {
          entityCode: entityCode.value,
          // entityType: childCode.value,
          entityType: entityType0,    //暂时只统计线索的逻辑
          //  data: [],
          list: [],
          companyId: userData.companyId,
          size: count === undefined ? 10 : count,
          page: count === undefined ? 1 : startRow / count + 1
        };

        target99.list.push({

          "propertyCode": "status",
          "propertyName": "",
          "propertyType": "",
          "propertyValue": "0",
          "propertyLength": "",
          "parmaFlag": "0",   //查询项

        });
        target99.list.push({

          "propertyCode": "accessory3",
          "propertyName": "",
          "propertyType": "",
          "propertyValue": "",
          "propertyLength": "",
          "parmaFlag": "1",   //分类项

        });

        target99.list.push({

          "propertyCode": "accessory4",
          "propertyName": "",
          "propertyType": "",
          "propertyValue": "",
          "propertyLength": "",
          "parmaFlag": "1",   //分类项

        });

        console.log("xpa参数输入1,target:", target);
        console.log("xpa参数输入1,target99:", target99);
        console.log("xpa参数输入1,userData:", userData);

        let flag999;    //明细标志

        flag999 = childCode.value.substring(childCode.value.length - 3, childCode.value.length);
        if (flag999 == '999') {


        } else {


          if (newArr.value.length != 0) {
            newArr.value.forEach(item => {
              Object.assign(target, item);
            });
          }
          target.data = originalParam.value;
          console.log("123123", originalParam)
          target.companyId = userData.companyId;

        }


        // if (entityCode.value == '808') {
        //   target.remark2 = userData.levelType; //如果是账户，以部门为单位查询
        // }

        //以部门为单位查询
        if (entityCode.value == '102' && childCode.value == '20') {
          if (userData.levelType == '000') {

          } else {
            //不是总部
            target.field0 = userData.levelType; //不是总部用户，只能查询自己部门
          }

        }


        if (entityCode.value == '102' && childCode.value == '09') {
          delete target.companyId;
        }
        if (fromdataUrl.value.indexOf('sub/getEntityTable') != -1) {
          store.commit('sphinx/updateServerGeneralStat', true)
        }
        if (entityCode.value === '802' && childCode.value === '0100' && rote.query.flag === "0") {
          postRequest("/transaction/account/selectAccountDtl", Object.assign(target, item), data => {
            searchFrame.value = [];
            a = false;
            // mulSelect.arr.length = 0;
            rows.value = transformFuncs(data);  // 表格数据
            // console.log("rows.value",rows.value);
            // pagination.value.rowsNumber = rows.value.length; // 数据总数
            loading.value = false;
          },);
        } else if (entityCode.value === '302' && childCode.value === '06' && rote.query.flag === "0") {
          postRequest(fromdataUrl.value, Object.assign(target, item), data => {
            searchFrame.value = [];
            a = false;
            // mulSelect.arr.length = 0;
            rows.value = transformFuncs(data);  // 表格数据
            // console.log("rows.value",rows.value);
            // pagination.value.rowsNumber = rows.value.length; // 数据总数
            loading.value = false;
          },);
        } else if (entityCode.value === '302' && childCode.value === '07' && rote.query.flag === "0") {
          postRequest(fromdataUrl.value, Object.assign(target, item), data => {
            searchFrame.value = [];
            a = false;
            // mulSelect.arr.length = 0;
            rows.value = transformFuncs(data);  // 表格数据
            // console.log("rows.value",rows.value);
            // pagination.value.rowsNumber = rows.value.length; // 数据总数
            loading.value = false;
          },);
        } else if ((
          (parentEntity?.entityCode === '102' && parentEntity?.childCode === '05')
          || (parentEntity?.entityCode === '102' && parentEntity?.childCode === '06')
          || (parentEntity?.entityCode === '301' && parentEntity?.childCode === '07')

        ) && rote.query.flag === "0") {
          console.log("xpa输入数据2，target99", target99);
          postRequest(fromdataUrl.value, Object.assign(target, item), data => {
            searchFrame.value = [];
            a = false;
            // mulSelect.arr.length = 0;
            rows.value = transformFuncs(data);  // 表格数据
            // console.log("rows.value",rows.value);
            // pagination.value.rowsNumber = rows.value.length; // 数据总数
            loading.value = false;
          },);
        } else if (fromdataUrl.value.indexOf("servers/general/") != -1) {

          console.log("xpa输入数据3，target9988", target99);
          if (childCode.value == '1299' || childCode.value == '1199') {
            console.log("xpa输入数据0，target99", target99);
            postRequest(fromdataUrl.value, Object.assign(target99, item), data => {
              searchFrame.value = [];
              a = false;
              // mulSelect.arr.length = 0;
              console.log("xpa输出数据99，data", data);
              rows.value = transformFuncs(data);  // 表格数据
              // console.log("rows.value",rows.value);
              // pagination.value.rowsNumber = rows.value.length; // 数据总数
              loading.value = false;
            },);

          } else {

            // if(flag999 == '999'){

            // let target999 = {
            //   entityNo: item.entityNo,
            // };
            //
            //
            // console.log("target1 999",target);
            //
            // console.log("xpa输入数据，target", target);
            // postRequest(fromdataUrl.value,target999 , data => {
            //   searchFrame.value = [];
            //   a = false;
            //   // mulSelect.arr.length = 0;
            //   console.log("xpa输出数据，data", data);
            //   rows.value = transformFuncs(data);  // 表格数据
            //   // console.log("rows.value",rows.value);
            //   // pagination.value.rowsNumber = rows.value.length; // 数据总数
            //   loading.value = false;
            // },);

            // }else {


            console.log("xpa输入数据，target", target);
            postRequest(fromdataUrl.value, Object.assign(target, item), data => {
              searchFrame.value = [];
              a = false;
              // mulSelect.arr.length = 0;
              console.log("xpa输出数据，data", data);
              rows.value = transformFuncs(data);  // 表格数据
              // console.log("rows.value",rows.value);
              // pagination.value.rowsNumber = rows.value.length; // 数据总数
              loading.value = false;
            },);




          }





        } else if (fromdataOption.value == 'get') {
          console.log("xpa输入数据3，target9977", target99);
          if (rote.query.flag == '0') {
            if (childCode.value.length == 5 || childCode.value.length == 4) {
              delete target.companyId;
              let requestBody
              if (rote.query.chanTial == '') {
                requestBody = {
                  "entityCode": rote.query.entityCode,
                  "entityType": rote.query.entityType,
                  "length": 1,
                  "isRoot": "0",
                  "propertyCode": rote.query.childCode,
                  "chainHead": "0",
                  "entityNo": rote.query.entityNo
                  //rowMsg.entityNo
                }
              } else {

                requestBody = {
                  "entityCode": rote.query.entityCode,
                  "entityType": rote.query.entityType.toString().substring(0, 2),
                  "length": 1,
                  "isRoot": "1",
                  "propertyCode": rote.query.childCode,
                  "chainHead": rote.query.chanTial,
                  "entityNo": rote.query.entityNo,
                }
              }
              console.log("xpa逻辑3");
              postRequest('/route/route/getEntityPropertyCodeChain', requestBody, async (res) => {
                let sceneCode = await getSceneCode();
                res.forEach((item, index, array) => {
                  item["isRoot"] = '1'
                  item["sceneCode"] = sceneCode
                })
                storeChainTemp = res
                // console.log("storeChainTemp暂未找到",storeChainTemp);

                let resBody = []
                codeValueArr = res;
                res.forEach((item, index, array) => {
                  resBody.push({ codeValue: item.codeValue })
                })
                resBody.forEach((item, index, array) => {
                  if (index == 0) {
                    fromdataUrl.value = fromdataUrl.value + '?codeValue=' + resBody[index].codeValue;
                  } else {
                    fromdataUrl.value = fromdataUrl.value + '&codeValue=' + resBody[index].codeValue;
                  }
                })
                getRequest(fromdataUrl.value, (res) => {
                  //@ts-ignore
                  tempArray = res
                  searchFrame.value = [];
                  //@ts-ignore
                  rows.value = transformFuncs(res);
                  loading.value = false;
                }, item)
              })
            } else {
              console.log('请求之前的数据', item)
              getRequest(fromdataUrl.value, data => {
                searchFrame.value = [];
                a = false;
                // mulSelect.arr.length = 0;
                console.log("xpa输出数据2，data", data);
                rows.value = transformFuncs(data);  // 表格数据
                // console.log("rows.value",rows.value);
                // pagination.value.rowsNumber = rows.value.length; // 数据总数
                loading.value = false;
              }, item);
            }
          } else {
            if (entityCode.value === '602' && childCode.value === '02') {
              postRequest(fromdataUrl.value, target, data => {
                searchFrame.value = [];
                a = false;
                // mulSelect.arr.length = 0;
                rows.value = transformFuncs(data);  // 表格数据
                // console.log("rows.value",rows.value);
                // pagination.value.rowsNumber = rows.value.length; // 数据总数
                loading.value = false;
              },);
            } else {
              console.log("xpa逻辑4");

              if (childCode.value == '1299') {
                console.log("xpa逻辑,target99", target99);
                getRequest(fromdataUrl.value, data => {
                  searchFrame.value = [];
                  a = false;
                  // mulSelect.arr.length = 0;
                  console.log("xpa输出数据3，data", data);
                  rows.value = transformFuncs(data);  // 表格数据
                  console.log("rows.value", rows);
                  // pagination.value.rowsNumber = rows.value.length; // 数据总数
                  loading.value = false;
                }, target99);

              } else {


                getRequest(fromdataUrl.value, data => {
                  searchFrame.value = [];
                  a = false;
                  let flag3 = '0';
                  // mulSelect.arr.length = 0;
                  console.log("xpa输出数据313，data", data);
                  rows.value = transformFuncs(data);  // 表格数据

                  //判断是否以楼层查询
                  console.log(" QueryBarCode.arr", QueryBarCode.arr);

                  if (entityCode.value === '510' && childCode.value === '42') {
                    console.log(" QueryBarCode.arr2", QueryBarCode.arr);
                    QueryBarCode.arr.forEach(x => {

                      console.log("x.valueOf()", x.valueOf());
                      flag3 = '1'

                    });


                  }
                  console.log("flag3", flag3);

                  if (entityCode.value === '510' && childCode.value === '42' && flag3 === '1') {

                    console.log("resultData", data);

                    let newArr = [];
                    let newArr2 = [];
                    let flag = '0';
                    let flag2 = '0';
                    if (data !== undefined && data !== null && data.length > 0) {

                      newArr.push({
                        name: 'accessory3',
                        label: '楼层',
                        field: 'accessory3'
                      })

                      newArr.push({
                        name: 'remark1',
                        label: '小区',
                        field: 'remark1'
                      })

                      newArr.push({
                        name: 'accessory5',
                        label: '部位',
                        field: 'accessory5'
                      })

                      newArr.push({
                        name: 'field6',
                        label: '工序',
                        field: 'field6'
                      })


                      data.forEach(item => {
                        // console.log("item",item);

                        flag = '0';
                        newArr.forEach(item1 => {
                          //判断区域是否相同
                          if (item1.label == item.accessory4) {
                            flag = '1';
                          }

                        });

                        if (flag === '0') {
                          newArr.push({ name: item.accessory4, label: item.accessory4, field: item.accessory4 });

                        }

                        flag2 = '0';
                        newArr2.forEach(item2 => {

                          if (item2.accessory3 == item.accessory3 && item2.remark1 == item.remark && item2.accessory5 == item.accessory5 && item2.field6 == item.field6) {

                            flag2 = '1';
                          }


                        });

                        if (flag2 === '0') {
                          newArr2.push({ accessory3: item.accessory3, remark1: item.remark, accessory5: item.accessory5, field6: item.field6, });


                        }






                      });





                      newArr2.forEach(item2 => {

                        data.forEach(item => {
                          console.log("data accessory4=", item.accessory4);
                          //每道工序完成比例赋值
                          if (item2.accessory3 == item.accessory3 && item2.remark1 == item.remark && item2.accessory5 == item.accessory5 && item2.field6 == item.field6) {
                            item2[item.accessory4] = item.number0;
                            // item2[item.companyId] = item.number1;

                          }

                        });



                      });



                    }

                    console.log("newArr501", newArr);
                    console.log("newArr2", newArr2);


                    columns.value = newArr;
                    console.log("columns", columns);

                    rows.value = transformFuncs(newArr2);  // 表格数据


                  }



                  console.log("rows.value", rows);
                  // console.log("rows.value",rows.value);
                  // pagination.value.rowsNumber = rows.value.length; // 数据总数
                  loading.value = false;
                }, target);
              }

            }


          }
        }
        if (fromdataOption.value == 'post') {
          console.log("xpa输入数据4，target99", target99);
          if (rote.query.flag == "0") {
            let reqBody = {
              "entityCode": rote.query.mainEntityCode,
              "entityType": rote.query.mainEntityType,
              "relationCode": rote.query.relationCode,
              "entityNo": rote.query.entityNo,
              "length": 1,
              "isRoot": "0",
              "chainHead": "0"
            }
            let url
            if (entityCode.value == "201" || entityCode.value == "102") {
              url = '/route/route/getAllEntityNoRelationTailToHeadChain'
            } else {
              url = '/route/route/getEntityNoRelationChain'
            }
            postRequest(url, reqBody, res => {
              let temp = []
              res.forEach((item, index, array) => {
                temp.push(item.entityNo)
              })
              postRequest(fromdataUrl.value, temp, res => {
                rows.value = transformFuncs(res);
              })
            })
          } else {

            if (childCode.value == '1299' || childCode.value == '1199') {
              console.log("xpa逻辑post,target99", target99);
              postRequest(fromdataUrl.value, target99, (data) => {
                searchFrame.value = [];
                a = false;
                data.forEach(i => {
                  if (i.serveNo) {
                    let serveNoc = i.serveNo.slice(0, 3) + '***' + i.serveNo.slice(-5);
                    i.serveNoC = serveNoc;
                  }
                });
                rows.value = transformFuncs(data);
                loading.value = false;
              });

            } else {
              postRequest(fromdataUrl.value, target, (data) => {
                searchFrame.value = [];
                a = false;
                data.forEach(i => {
                  if (i.serveNo) {
                    let serveNoc = i.serveNo.slice(0, 3) + '***' + i.serveNo.slice(-5);
                    i.serveNoC = serveNoc;
                  }
                });
                rows.value = transformFuncs(data);
                console.log("rows=", rows.value);
                loading.value = false;
              });


            }



          }
        }
        loading.value = false;
      }

    }

    /**
     * 计算分页
     * @param filter
     */
    function getRowsNumberCount(filter: string): number {
      let count = 0;
      if (originalRows.value !== undefined) {
        if (!filter) {
          return originalRows.value.length;
        }
        originalRows.value.forEach((treat: OriginalRows) => {
          if (treat.name.includes(filter)) {
            ++count;
          }
        });
      }
      return count;
    }
    function transformFuncs(inData) {
      inData.forEach(x => {
        for (var key in x) {
          translate.forEach(a => {
            if (a.propertyEnglish == key && a.value == x[key]) {
              x[key] = a.valueName
            }
          })
        }
      })
      rowsTemp = JSON.parse(JSON.stringify(inData))
      return inData
    }
    /**
     * 数据请求
     * @param props
     */
    function onRequest(props: Props) {
      const { page, rowsPerPage, sortBy, descending } = props.pagination;
      // console.log("props.pagination",props.pagination);

      const filter = props.filter;
      loading.value = true;
      // emulate server
      setTimeout(() => {
        // update rowsCount with appropriate value
        // pagination.value.rowsNumber = getRowsNumberCount(filter);
        // console.log("pagination.value.rowsNumber",pagination.value.rowsNumber);
        pagination.value.rowsNumber = 10000
        // get all rows if "All" (0) is selected
        const fetchCount = rowsPerPage === 0 ? pagination.value.rowsNumber : rowsPerPage;
        // calculate starting row of data
        const startRow = (page - 1) * rowsPerPage;
        // fetch data from "server"
        fetchFromServer(startRow, fetchCount, filter, sortBy, descending);
        // clear out existing data and add new
        // don't forget to update local pagination object
        pagination.value.page = page;
        pagination.value.rowsPerPage = rowsPerPage;
        pagination.value.sortBy = sortBy;
        pagination.value.descending = descending;
      }, 10);
    }

    /**
     * 获取操作项
     */
    function getOperation() {
      let sceneCode = ''
      let requestSceneBody = [
        {
          "entityCode": '101',
          "codeName": '',
          "entityType": '01',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": null,
          "propertyChinese": null,
          "propertyValue": null,
          "propertyCondition": null,
          "companyId": userData.companyId
        },
        {
          "entityCode": '102',
          "codeName": '',
          "entityType": '02',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": 'roleType',
          "propertyChinese": null,
          "propertyValue": userData.roleType,
          "propertyCondition": null,
          "companyId": userData.companyId
        }];
      api.post('/channel/channel/getSceneCode', requestSceneBody).then(res => {
        if (res.status == 200) {
          sceneCode = res.data.data;
          let reqData = reactive({});
          if (entityCode.value !== undefined) {
            reqData = {
              entityCode: entityCode.value,
              entityType: childCode.value,
              sceneCode: sceneCode,
              objectCodeType: '104',
              companyId: userData.companyId,
              groupEntityCode: '101'
            };
            postRequest('channel/channel/operation', reqData, setOperation);
          }
        }
      })
    }

    /**
     * 设置操作项
     * @param data
     */
    function setOperation(data: Operation[]) {
      if (data !== null && data.length > 0) {
        let selections: recOperation[] = [];
        let global: recOperation[] = [];
        data.forEach((x: Operation) => {
          if (x.operateEvent === '002' && x.operateEntity == (entityCode.value + childCode.value)) {
            global.push({ operateEventName: x.operateEventName, operateEvent: x.operateEvent, operateEntity: x.operateEntity });
          } else if (x.operateEvent === '402' && x.operateEntity == (entityCode.value + childCode.value)) {
            global.push({ operateEventName: x.operateEventName, operateEvent: x.operateEvent, operateEntity: x.operateEntity });
          } else {
            selections.push({ operateEventName: x.operateEventName, operateEvent: x.operateEvent, operateEntity: x.operateEntity });
          }
        });
        operationFirstSelections.value = selections.splice(0, 1)[0];
        operationSelections.value = selections;
        globalOperation.value = global;
      } else {
        operationFirstSelections.value = { operateEventName: '', operateEvent: '', operateEntity: "" }
        operationSelections.value = [{ operateEventName: '', operateEvent: '', operateEntity: "" }]
        globalOperation.value = [{ operateEventName: '', operateEvent: '', operateEntity: "" }]
      }
    }

    /**
     * 通过地址栏获取传来的实体代码entityCode
     */
    function setApiByInterfaceEnglish() {

      entityCode.value = <string>rote.query.entityCode;
      childCode.value = <string>rote.query.childCode;
      if (childCode.value === undefined) {
        childCode.value = '';
      }
    }

    /**
     * 组合请求
     */
    function requestTableData() {

      setApiByInterfaceEnglish();//获取路由地址的主体代码和子主体代码
      requestColumns();

      // get initial data from server (1st page)
      getOperation();
      getRelation();
    }
    // 监听一下path
    // watch(
    //   ()=>path.value,(newValue,oldValue)=>{
    //     console.log("newValue",newValue);
    //     console.log("oldValue",oldValue);

    //   }
    // ),
    // onBeforeMount(()=>{
    //   path.value = localStorage.getItem("path")
    //   // console.log("beforepath",path.value);

    // })

    onMounted(async () => {
      // console.log("route",rote);
      /**************************************************************/
      // setTimeout(() => {
      //   localStorage.setItem("path",router.currentRoute.value.fullPath)  // 将当前地址存到localstorage中
      // }, 50);
      // console.log("setPath",path.value);

      // pathArr.push(localStorage.getItem("path"))

      // path.value = router.currentRoute.value.fullPath
      // console.log("path",path.value);

      //数据初始化
      //缓存清除
      operationFirstSelections.value = { operateEventName: '', operateEvent: '', operateEntity: "" }
      operationSelections.value = [{ operateEventName: '', operateEvent: '', operateEntity: "" }]
      globalOperation.value = [{ operateEventName: '', operateEvent: '', operateEntity: "" }]
      requestTableData();
      store.commit('sphinx/updateServerGeneralStat', false)
    });

    //跳转到活动详细页面
    function ToactivityDetails(i) {
      // console.log("iiiiiiii",i);
      void router.push('/activityDetails?entityCode=' + entityCode.value + '&serveNo=' + i);
    }

    //去往类型页面
    function toType() {
      if (entityCode.value !== undefined) {

        void router.push('/Type?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '00');
      }
    }

    // 存储数据
    function setUserDetail(data) {
      //存储车辆下面系统数据
      if (entityCode.value === "201" && childCode.value === "02") {
        store.commit('sphinx/storeSystemInfo', data)
      } else if (entityCode.value === "303" && childCode.value === "01") {
        store.commit('sphinx/storeOrderInfo', data)
      } else {
        store.commit('sphinx/updateCarstate', data);
      }
    }

    // 去往详情页面
    function toDetail(p: any) {
      // console.log("去详情");
      console.log("p1p1p1p", p);

      setUserDetail(p);//将这一行的详细信息存储在vuex
      if (entityCode.value !== undefined) {
        void router.push('/Detail?entityCode=' + entityCode.value + '&childCode=' + childCode.value);
      }
    }

    //操作项的第一个选项
    function topOperation(p: any, item: any) {
      localStorage.setItem('currentBody',JSON.stringify(p))
      // console.log(p,item)
      p.operateEventName = item.operateEventName;
      // console.log('传过去的数据', p); // 可以拿到这一行的id
      // console.log("item",item);
      //存储当前主体编号
      store.commit('sphinx/updateCurrentOptEntity', { entityCode: entityCode.value, childCode: childCode.value })
      console.log('当前主体编号', { entityCode: entityCode.value, childCode: childCode.value })
      // alert("xpa1")
      //存储当前选中行
      store.commit('sphinx/updatePrevOpt', p);
      console.log('选中行数据', p)
      setUserDetail(p);
      //存储当前页面请求参数
      store.commit('sphinx/upratePrevUrl', location.href.split('?')[1]);
      console.log('存储当前页面URL参数', location.href.split('?')[1])
      if (item.operateEvent == '415') {
        void router.push(p.remark2);    //跳转到remark2
        return;
      }

      if (item.operateEvent == '022') {
        void router.push('/Permissions');
      }
      if (item.operateEvent !== '022' && entityCode.value !== undefined) {
        //void router.push('/Option?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '&operateEvent=' + item.operateEvent);
        //跳转至操作页面
        // alert("xpa1112")
        console.log('操作页面参数', '/Option?entityCode=' + item.operateEntity.substring(0, 3) + '&childCode=' + item.operateEntity.substring(3) + '&operateEvent=' + item.operateEvent + '&operateEventName=' + item.operateEventName)

        // void router.push('/Add?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '&operateEvent=' + item.operateEvent);
        // if (item.operateEvent == '002'){

        //  void router.push('/Add?entityCode=' + item.operateEntity.substring(0,3) + '&childCode=' + item.operateEntity.substring(3) + '&operateEvent=' + item.operateEvent+ '&operateEventName=' + item.operateEventName);
        //   }else{
        void router.push('/Option?entityCode=' + item.operateEntity.substring(0, 3) + '&childCode=' + item.operateEntity.substring(3) + '&operateEvent=' + item.operateEvent + '&operateEventName=' + item.operateEventName);
        //   }


      }
    }

    function toAdd(item) {
      if (entityCode.value == "303" && childCode.value == "01") {
        void router.push('/addOrders?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '&operateEvent=' + item.operateEvent)
      } else if (item.operateEvent == "402") {
        const param = { "entityCode": entityCode.value, "entityType": childCode.value, "theirEventCode": "402" }
        postRequest(getInterface, param, res => {
          let typeName = res.data.typeName;
          let url = res.data.interfaceEnglish;
          let s = url.substr(url.indexOf('/') + 1);
          let now = new Date();
          let t_s = now.getTime();
          now.setTime(t_s - 1000 * 60 * 60 * 24 * 30);
          const reqParam = {
            // "startDate": dateFormatter(now),
            // "endDate": dateFormatter(new Date()),
            "entityCode": entityCode.value,
            "entityType": childCode.value,
            "companyId": userData.companyId
          }
          postRequest(s, reqParam, (res) => {
            const data = res.data;
            const datum = data[0];
            let excelColumn = []
            for (let key in datum) {
              excelColumn.push({ name: key, label: key })
            }
            let values = data;
            export2Excel(typeName, excelColumn, values)
          })
        });
      } else {
        void router.push('/Add?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '&operateEvent=' + item.operateEvent);
      }
    }

    function dateFormatter(date: Date) {
      let Y = date.getFullYear() + '-',
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-',
        D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ',
        h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':',
        m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':',
        s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
      return Y + M + D
    }
    let indexItem = ref(null);
    let entityNo = ref('')
    // 去往关系页面
    async function toRelation(p: any, item: any) {
      emit('rightInfo',{
        opName:'showAndRefreshRight',
        bodyInfo:p
      })
      let routerPath = JSON.parse(JSON.stringify(store.state.sphinx.routerPath));
      //当前记录数据存储到VUEX store
      console.log('选中行', p)
      console.log('当前url地址', routerPath)
      routerPath.push(window.history.state.current)
      store.commit('sphinx/updateRouterPath', routerPath);//地址
      console.log('当前主体编号', { entityCode: entityCode.value, childCode: childCode.value })
      store.commit('sphinx/updatePrevOptEntity', { entityCode: entityCode.value, childCode: childCode.value })//当前实体编号
      let seletedItem = JSON.parse(JSON.stringify(store.state.sphinx.selectedItemData));
      console.log('关系堆栈', seletedItem)
      seletedItem.push(JSON.parse(JSON.stringify(p)))//选中行

      store.commit('sphinx/updateSelectedItemData', seletedItem);

      let parentEntity = JSON.parse(JSON.stringify(store.state.sphinx.parentEntity));
      parentEntity.push({ entityCode: entityCode.value, childCode: childCode.value })

      store.commit('sphinx/updateParentEntity', parentEntity);
      // console.log("ppppp",p);
      // console.log("relationFirstSelection.arr",relationFirstSelection.arr);
      // console.log("relationFirstSelection",relationFirstSelection);
      // console.log("item",item);

      let sceneCode = await getSceneCode();
      // console.log("sceneCode",sceneCode);
      let flagName
      if (entityCode.value == "301" && childCode.value == "01110") {
        flagName = 'serveRangeCode'
      }
      if (entityCode.value == "301" && childCode.value == "01120") {
        flagName = 'systemCode'
      }
      if (entityCode.value == "301" && childCode.value == "01100") {
        flagName = 'basicsCode'
      }
      if (entityCode.value == "301" && childCode.value == "01111") {
        flagName = 'serveAgingCode'
      }
      if (entityCode.value == "301" && childCode.value == "01122") {
        flagName = 'warrantyCode'
      }
      if (entityCode.value == "301" && childCode.value == "01123") {
        flagName = 'deadlineCode'
      }
      if (entityCode.value == "301" && childCode.value == "01131") {
        flagName = 'paymentsCode'
      }
      if (entityCode.value == "301" && childCode.value == "01141") {
        flagName = 'selfAmtCode'
      }
      if (entityCode.value == "301" && childCode.value == "01114") {
        flagName = 'accessoryCode'
      }
      if (entityCode.value == "301" && childCode.value == "01112") {
        flagName = 'attributeNo'
      }
      if (entityCode.value == "301" && childCode.value == "01190") {
        flagName = 'codeValue'
      }
      if (entityCode.value == "301" && childCode.value == "01131") {
        flagName = 'paymentsCode'
      }
      if (entityCode.value == "201" && childCode.value == "02110") {
        flagName = 'unitNo'
      }
      if (entityCode.value == "201" && childCode.value == "02120") {
        flagName = 'unitNo'
      }
      if (entityCode.value == "301" && childCode.value == "01115") {

        flagName = 'priceNo'
      }
      if (entityCode.value == "701") {
        flagName = "serveNo"
      }
      let indexNum
      storeChainTemp.forEach((item1, index, array) => {

        if (item1.codeValue == p[flagName]) {
          indexNum = index
        }
      })
      let entityN = ''
      let entityNa = ''
      if (entityCode.value == '301' && childCode.value == '01') {
        entityN = p.seriesNo;
        entityNa = p.seriesName
        // 赋值
      }
      // if(entityCode.value =='302' && childCode.value == '01'){
      //   entityN = p.agreementNo;
      //   entityNa = p.agreementName;
      // }
      if (entityCode.value == '201' && childCode.value == '02') {
        entityN = p.unitNo;
        entityNa = p.unitName;
      }
      if (entityCode.value == '701') {
        entityN = p.serveNo;
        entityNa = p.serveName;
      }
      if (entityCode.value == '201' && childCode.value == '') {
        entityN = p.carNo;
        entityNa = p.carName;
      }
      if (entityCode.value == '303' && childCode.value == '02') {
        entityN = p.orderNo;
        entityNa = p.orderName;
      }
      if (childCode.value.length == 2) {
        let temp = {
          chainHead: '',
          chainTail: '',
          codeName: '',
          codeValue: '',
          codeValueName: entityNa,
          entityCode: entityCode.value,
          entityNo: entityN,
          entityType: childCode.value,
          gmtCreate: '',
          gmtModify: '',
          id: '',
          propertyCode: '',
          propertyCodeName: '',
          typeName: '',
          isRoot: '0',
          sceneCode: sceneCode
        }
        store.commit('sphinx/storeChain', temp);
      } else {
        if (childCode.value.length == 2) {
          storeChainTemp[indexNum].entityNo = entityN;
          storeChainTemp[indexNum].codeValueName = entityNa;
        }
        store.commit('sphinx/storeChain', storeChainTemp[indexNum]);
      }
      store.commit('sphinx/updateRelation', item);
      setUserDetail(p);
      if (rote.query.chanTial) {
        //@ts-ignore
        // childCode.value = rote.query.entityType
      }

      indexItem.value = codeValueArr.findIndex((element) => element.codeValue == p[flagName])
      if (codeValueArr[indexItem.value] !== undefined) {
        chainTail.value = codeValueArr[indexItem.value].chainTail
        entityNo.value = codeValueArr[indexItem.value].entityNo
      }
      if (entityCode.value !== undefined) {
        if (entityCode.value == '201' && childCode.value == '01') {
          void router.push('/Relation?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '&otherEntityType=' + item.otherEntityType);
        } else if (childCode.value.length == 5) {
          void router.push('/');
          setTimeout(() => {
            void router.push('/list?entityCode=' + item.otherEntityCode + '&childCode=' + item.otherEntityType + '&entityType=' + childCode.value + '&chanTial=' + chainTail.value + '&entityNo=' + entityNo.value + '&flag=' + 0);
          }, 10)
        } else {
          void router.push('/');
          setTimeout(() => {
            //跳转至目标主体页面
            console.log('跳转至目标主体页面', '/list?entityCode=' + item.otherEntityCode + '&childCode=' + item.otherEntityType + '&entityType=' + childCode.value + '&chanTial=' + chainTail.value + '&entityNo=' + entityN + '&flag=' + 0 + '&mainEntityCode=' + item.entityCode + '&mainEntityType=' + item.entityType + '&relationCode=' + item.relationCode)
            void router.push('/list?entityCode=' + item.otherEntityCode + '&childCode=' + item.otherEntityType + '&entityType=' + childCode.value + '&chanTial=' + chainTail.value + '&entityNo=' + entityN + '&flag=' + 0 + '&mainEntityCode=' + item.entityCode + '&mainEntityType=' + item.entityType + '&relationCode=' + item.relationCode);
          }, 10)
        }
      }
    }

    //存储产品属性主体需要用到的所有信息
    function saveMessage(p, item) {

    }

    // 去往C端报告页面
    function toCreport(p: any, item: any) {
      setUserDetail(p);
      window.open(`/kungfu/report?uuid=${p.uuid}`)
      //void router.push(`/kungfu/report?uuid=${p.uuid}`)
    }
    function toCert(p: any, item: any) {
      setUserDetail(p);
      window.open(`/kungfu/cert?uuid=${p.uuid}`)
      //void router.push(`/kungfu/cert?uuid=${p.uuid}`)
    }
    function toNewCert(p: any, item: any) {
      setUserDetail(p);
      window.open(`/report/report?uuid=${p.uuid}`)
    }
    function toNewCertPaint(p: any, item: any) {
      setUserDetail(p);
      window.open(`/report/reportPaint?uuid=${p.uuid}`)
    }
    function toSanwuReport(p: any, item: any) {
      setUserDetail(p);
      window.open(`/report/reportSanwu?uuid=${p.uuid}`)
    }
    function toReportCover(p: any, item: any) {
      setUserDetail(p);
      window.open(`/report/reportCover?uuid=${p.uuid}`)
    }
    const orderNowStat = ref(false)
    function bindItems(rows) {
      // console.log("rowsrows",rows);

      const uuid = rows.uuid;
      // console.log("uuiduuid",uuid);
      getRequest("/detection/detection/CExhibition?keyword=" + uuid, (res) => {
        // console.log("resresres",res); // 返回值为空 应该是后端没有数据

        if (res[0].status_name === "已完成") {
          orderNowStat.value = true
        } else {
          orderNowStat.value = false
        }
      })
    }

    function getSceneCode() {
      let requestSceneBody = [
        {
          "entityCode": '101',
          "codeName": '',
          "entityType": '01',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": null,
          "propertyChinese": null,
          "propertyValue": null,
          "propertyCondition": null,
          "companyId": userData.companyId
        },
        {
          "entityCode": '102',
          "codeName": '',
          "entityType": '02',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": 'roleType',
          "propertyChinese": null,
          "propertyValue": userData.roleType,
          "propertyCondition": null,
          "companyId": userData.companyId
        }];
      return new Promise((resolve, reject) => {
        api.post('/channel/channel/getSceneCode', requestSceneBody).then(res => {
          resolve(res.data.data);
        }).catch(err => {
          reject(err);
        })
      });
    }
    function jumpToUrl(url: string) {
      window.open(url)
    }

    function exportHr() {
      getRequest('/party/personnel/transEntryPersonALL?companyId=9999,', (res) => {
        let columns1 = res.columns;
        let values = res.values;
        let excelColumn = []
        for (var key in columns1) {
          columns1[key]
          excelColumn.push({ name: key, label: columns1[key] })
        }
        export2Excel("人事清单表", excelColumn, values)
      })
    }

    function printData() {
      let tableColumns = columns.value.slice(1, columns.value.length - 2);
      tableColumns.forEach(x => {
        x.displayName = x.label
      })

      printJS({
        printable: rows.value,
        properties: tableColumns,
        type: 'json',
        gridHeaderStyle: 'border: 1px solid #000;text-align:center',
        gridStyle: 'border: 1px solid #000;text-align:center'
      })
    }
    function batchUpdate() {
      const promises = []
      rowsTemp.forEach((x, y) => {
        const original = JSON.stringify(x);
        const modified = JSON.stringify(rows.value[y]);
        if (original !== modified) {
          promises.push(updateEntryGeneral(rows.value[y]))
        }

      })
      Promise.all(promises).then(() => {
        alert("提交成功")
      })

    }
    function updateEntryGeneral(inData) {
      inData.eventCode = "003";
      return api.post('/servers/general/updateEntryGeneral', inData)
    }
    function editAble(name: string, accessory3: string) {
      let editable = false
      if (name.indexOf("number") !== -1 && accessory3 && accessory3.length > 0) {
        const nameElement = name[name.length - 1];
        editable = !!Number(accessory3[nameElement])
      }
      return editable;
    }
    watch(() => rows.value,
      (newValue, oldValue) => {
        if (oldValue !== undefined && oldValue.length > 0) {
          const news = JSON.stringify(newValue);
          const olds = JSON.stringify(rowsTemp);
          rowsTemp.forEach((x, y) => {
            const original = JSON.stringify(x);
            const valueElement = rows.value[y];
            const modified = JSON.stringify(valueElement);
            for (const key in x) {
              if (x[key] !== valueElement[key] && key !== 'remark1') {

                valueElement.remark1 = key
                updateEntryGeneral(valueElement)
                rowsTemp = JSON.parse(JSON.stringify(newValue))
              }
            }

          })
        }

      },
      {
        deep: true
      })
    return {
      entityNo,
      qdateShow,
      qdateModel,
      qdateRangeEnd,
      filter,
      loading,
      pagination,
      columns,
      rows,
      operationFirstSelections,
      operationSelections,
      globalOperation,
      getOperation,
      onRequest,
      toType,
      entityCode,
      toDetail,
      goBack,
      toAdd,
      toRelation,
      toCreport,
      toCert,
      topOperation,
      getFromdataUrl,
      fromdataUrl,
      mouseover,
      indexItem,
      searchFrame,
      onQueryBar,
      searchFrameArr,
      searchFrameArr1,
      mulSelect,
      searchClick,
      fetchFromServer,
      childCode,
      userData,
      relationFirstSelection,
      relationSelection,
      ToactivityDetails,
      codeValueArr,
      handelValue,
      carNo,
      options,
      searchVale,
      selections,
      bindItems,
      orderNowStat,
      jumpToUrl,
      toNewCert,
      originalParam,
      toNewCertPaint,
      export2Excel,
      exportHr,
      toSanwuReport,
      toReportCover,
      printData,
      batchUpdate,
      pageDataModified,
      editAble
    };
  },
  methods: {
    handleTableRowClick(e) {
      this.$emit('rightInfo', {
        opName: 'showAndRefreshRight',
        bodyInfo: JSON.parse(JSON.stringify(e))
      })
    }
  }
});
</script>
<style lang='sass' scoped>
.control-btn
  padding-left: 1em
  padding-right: 1em
  margin: 0.5em

.sticky-col
  position: sticky
  right: 0
  z-index: 1
  background-color: white

.detail
  text-decoration: none
  color: #fff
.inBigTitle
  margin-right: 3em
</style>
